package com.todod.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.todod.common.util.SnowflakeIdGenerator;
import com.todod.mapper.UserRoleMapper;
import com.todod.model.UserRole;
import com.todod.service.IUserRoleService;

/**
 * @author lql
 * @date 2021年1月26日
 */
@Service
@Transactional
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {

	@Override
	public UserRole getByUserId(Long userId) {
		QueryWrapper<UserRole> wrapper = new QueryWrapper<UserRole>();
		wrapper.eq("sur_user_id", userId);
		return getOne(wrapper);
	}

	@Override
	public void editRole(Long userId, UserRole userRole) {

		UserRole ur = getByUserId(userRole.getUserId());

		if (ur == null) {
			userRole.setId(SnowflakeIdGenerator.getId());
			userRole.setCreateUserId(userId);
			userRole.setCreateTime(LocalDateTime.now());

			save(userRole);
		} else {
			ur.setRoleId(userRole.getRoleId());

			updateById(ur);
		}

	}

	@Override
	public List<UserRole> getByRoleId(Long roleId) {
		QueryWrapper<UserRole> wrapper = new QueryWrapper<UserRole>();
		wrapper.eq("sur_role_id", roleId);
		List<UserRole> list = baseMapper.selectList(wrapper);
		return list;
	}

	@Override
	public List<UserRole> getByRoleIdBesidesUserId(Long roleId, Long _userId) {
		QueryWrapper<UserRole> wrapper = new QueryWrapper<UserRole>();
		wrapper.eq("sur_role_id", roleId);
		wrapper.ne("sur_user_id", _userId);
		List<UserRole> list = baseMapper.selectList(wrapper);
		return list;
	}

}
